<template>
  <div class="app-container">
    <el-row :gutter="20">

      <!--用户数据-->
      <el-col :span="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="团长名称" prop="realName">
            <el-input
              v-model="queryParams.realName"
              placeholder="请输入团长名称"
              clearable
              size="small"
              style="width: 160px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phoneNumber">
            <el-input
              v-model="queryParams.phoneNumber"
              placeholder="请输入手机号码"
              clearable
              size="small"
              style="width: 160px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="微信号" prop="wechat">
            <el-input
              v-model="queryParams.wechat"
              placeholder="请输入微信号码"
              clearable
              size="small"
              style="width: 160px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="开拓者" prop="trailblazer">
            <el-input
              v-model="queryParams.trailblazer"
              placeholder="请输入开拓者"
              clearable
              size="small"
              style="width: 160px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
<!--          <el-form-item label="注册时间">-->
<!--            <el-date-picker-->
<!--              v-model="dateRange"-->
<!--              size="small"-->
<!--              style="width: 215px"-->
<!--              value-format="yyyy-MM-dd"-->
<!--              type="daterange"-->
<!--              range-separator="-"-->
<!--              start-placeholder="开始日期"-->
<!--              end-placeholder="结束日期"-->
<!--            ></el-date-picker>-->
<!--          </el-form-item>-->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>


        <el-table v-loading="loading" :data="userTypeList" @queryTable="getTypeList">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="团长名称" align="left" key="realName" prop="realName" v-if="columns[1].visible"/>
          <el-table-column label="手机号码" align="center" key="phoneNumber" prop="phoneNumber" v-if="columns[2].visible"/>
          <el-table-column label="微信号" align="center" key="wechat" prop="wechat" v-if="columns[3].visible"/>
          <el-table-column label="注册时间" align="center" key="createTime" prop="createTime" v-if="columns[6].visible"
                           width="170">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="邀请码" align="center" key="inviteCode" prop="inviteCode"/>
          <el-table-column label="累计推广" align="center" key="inviteCount" prop="inviteCount"/>
          <el-table-column label="本月推广" align="center" key="imcount" prop="imcount"/>
          <el-table-column label="累计收益" align="center" key="inviteAmount" prop="inviteAmount"/>
          <el-table-column label="开拓者" align="center" key="trailblazer" prop="trailblazer" v-if="columns[4].visible"/>
          <el-table-column label="门牌照片" align="headPhoto" prop="headPhoto" v-if="columns[5].visible">
            <template slot-scope="scope">
              <el-image v-if="scope.row.headPhoto"
                        style="width: 80px; height: 40px;"
                        :src="scope.row.headPhoto">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="详细地址" align="center" prop="address" v-if="columns[6].visible"/>
          <el-table-column label="备注" align="center" prop="comment" v-if="columns[7].visible"/>
          <el-table-column
            label="操作"
            align="center"
            width="260"
            class-name="small-padding fixed-width"
          >

            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改
              </el-button>
              <template>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-document"
                  @click="handleInviteList(scope.row)"
                >推广明细
                </el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="TypeTotal>0"
          :total="TypeTotal"
          :page.sync="queryTypeParams.pageNum"
          :limit.sync="queryTypeParams.pageSize"
          @pagination="getTypeList"
        />
      </el-col>
    </el-row>

    <el-dialog title="推广列表" :visible.sync="orderOpen" width="60%" append-to-body>
      <el-tabs v-model="tabActiveName" @tab-click="handleTabClick">
        <el-tab-pane label="用户信息" name="first">
          <el-table id="0" :data="userList1" >
            <el-table-column label="用户名称" align="center" >
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="handleOrderList(scope.row)"
                >{{scope.row.nickName}}</el-button>
              </template>
            </el-table-column>
            <el-table-column label="用户性别" align="center" prop="sex" :formatter="sexFormat"/>
            <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber"/>
            <el-table-column label="推广时间" align="center" prop="inviteTime">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.inviteTime) }}</span>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="userTotal>0"
            :total="userTotal"
            :page.sync="queryInviteParams.pageNum"
            :limit.sync="queryInviteParams.pageSize"
            @pagination="getInviteUserList"/>
        </el-tab-pane>
        <el-tab-pane label="订单信息" name="second">
          <el-table id="1" :data="userOrderList">
            <el-table-column label="订单编号" align="center" prop="num"/>
            <el-table-column label="订单名称" align="center" prop="attribute"/>
            <el-table-column label="订单金额" align="center" prop="pay">
            </el-table-column>
          </el-table>
          <pagination
            v-show="userOrderTotal>0"
            :total="userOrderTotal"
            :page.sync="queryOrderParams.pageNum"
            :limit.sync="queryOrderParams.pageSize"
            @pagination="getOrderList"/>
        </el-tab-pane>
      </el-tabs>
<!--      <div slot="footer" class="dialog-footer">-->
<!--        <el-button @click="cancel">取 消</el-button>-->
<!--      </div>-->
    </el-dialog>

    <el-dialog title="信息修改" :visible.sync="updateOpen" width="50%" append-to-body>
      <el-form label-width="120px">

        <el-row>
          <el-col :span="12">
            <el-form-item label="开拓者" prop="trailblazer">
              <el-input v-model="form.trailblazer" placeholder="请输入开拓者姓名"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入详细地址"/>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="团长名称" prop="realName">
              <el-input v-model="form.realName" placeholder="请输入团长名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信号" prop="wechat">
              <el-input v-model="form.wechat" placeholder="请输入微信号"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">

          <el-col :span="12">
            <el-form-item label="门牌照片" prop="headPhoto">
              <ImageUpload v-model="form.headPhoto"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="comment">
              <el-input v-model="form.comment" placeholder="请输入备注信息"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row slot="footer" class="dialog-footer" style="text-align:center;" type="flex" justify="center">
        <el-col :span="10">
          <el-button type="primary" @click="edit" v-if="!disabled">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </el-col>
      </el-row>
    </el-dialog>

  </div>
</template>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

<script>
  import {listUserType, selectUserTypeById, updateUserTypeById, addUserType} from "@/api/system/userType";
  import {listUser, listInviteUser, changeUserStatus, getUser, updateUser} from "@/api/system/user";
  import {getToken} from "@/utils/auth";
  import ImageUpload from '@/components/ImageUpload';
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import {listOrder, listUserOrder, listUserReceive} from "@/api/business/order";

  export default {
    name: "User",
    components: {
      Treeselect,
      ImageUpload
    },
    data() {
      return {
        pType: '',
        raw2: "",
        tabActiveName: "first",
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        disabled: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        orderTotal: 0,
        TypeTotal: 0,
        userTotal: 0,
        userOrderTotal: 0,
        receiveTotal: 0,
        // 用户表格数据
        userList: null,
        userList1: null,
        userTypeList: null,
        addressList: null,
        orderList: null,
        userOrderList: null,
        receiveList: null,
        bankcardList: null,
        // 弹出层标题
        title: "",
        // 部门树选项
        deptOptions: undefined,
        // 是否显示弹出层
        open: false,
        addressOpen: false,
        orderOpen: false,
        updateOpen: false,
        typeOpen: false,
        bankcardOpen: false,
        // 部门名称
        deptName: undefined,
        // 默认密码
        initPassword: undefined,
        user: null,
        // 日期范围
        dateRange: [],
        // 状态数据字典
        statusOptions: [],
        //推广人类别字典
        typeOptions: [],
        // 性别状态字典
        sexOptions: [],
        // 岗位选项
        postOptions: [],
        // 角色选项
        roleOptions: [],
        // 表单参数
        form: {
          uid:null
        },
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: {Authorization: "Bearer " + getToken()},
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/system/user/importData"
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          realName: undefined,
          phonenumber: undefined,
          wechat: undefined,
          peopleType: undefined,
          trailblazer: undefined
        },
        queryTypeParams: {
          pageNum: 1,
          pageSize: 10,
          realName: undefined,
          phonenumber: undefined,
          wechat: undefined,
          peopleType: undefined,
          trailblazer: undefined
        },
        queryOrderParams: {
          pageNum: 1,
          pageSize: 5,
        },
        queryReceiveParams: {
          pageNum: 1,
          pageSize: 5,
        },
        queryInviteParams: {
          pageNum: 1,
          pageSize: 5,
          inviteUserId: undefined,
          userName: undefined,
          phonenumber: undefined,
          status: undefined,
          peopleType: undefined,
          deptId: undefined
        },
        // 列信息
        columns: [
          {key: 0, label: `团长账号`, visible: true},
          {key: 1, label: `团长名称`, visible: true},
          {key: 2, label: `手机号码`, visible: true},
          {key: 3, label: `微信号`, visible: true},
          {key: 4, label: `开拓者`, visible: true},
          {key: 5, label: `门牌照片`, visible: true},
          {key: 6, label: `详细地址`, visible: true},
          {key: 7, label: `备注`, visible: true},
          {key: 9, label: `邀请码`, visible: true}
        ],
      };
    },

    created() {
      this.getTypeList();
      // this.getTreeselect();
      this.getDicts("sys_normal_disable").then(response => {
        this.statusOptions = response.data;
      });
      this.getDicts("sys_leader_general").then(response => {
        this.typeOptions = response.data;
      });
      this.getDicts("sys_user_sex").then(response => {
        this.sexOptions = response.data;
      });
      this.getConfigKey("sys.user.initPassword").then(response => {
        // this.initPassword = response.msg;
      });
    },
    methods: {

      /** 修改按钮操作 */
      handleShow(row) {
        //console.log(row)
        this.updateOpen = true;
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.updateOpen = true;
        const id = row.userId || this.ids
        this.form.uid = id;
        selectUserTypeById(id).then(response => {
          this.form = response.data;
          console.log(this.form)
          this.open = true;
          this.title = "修改文章管理";
        });
      },
      /** 修改确定按钮操作 */
      edit() {
        console.log(this.form)
        updateUserTypeById({
          ...this.form
        }).then(response => {
          // console.log(data)
          this.msgSuccess("修改成功");
          this.getTypeList();
          this.updateOpen = false;
        });

      },
      // edit() {
      //   let that = this;
      //   let data = this.form;
      //   console.log(that);
      //   this.$confirm('是否确认修改?', "警告", {
      //     confirmButtonText: "确定",
      //     cancelButtonText: "取消",
      //     type: "warning"
      //   }).then(function() {
      //     updateUserTypeById(this.form).then(response => {
      //       this.msgSuccess("修改成功");
      //       this.getList();
      //     });
      //     this.updateOpen = false;
      //   });
      // },
      /** 查看地址操作 */
      handleOrderList(row) {
        console.log(row)
        this.tabActiveName = "second"
        const userId = row.userId || this.ids;
        this.orderOpen = true;
        this.userOrderList = null;
        this.receiveList = null;
        this.$nextTick(() => {
          getUser(userId).then(response => {
            this.form = response.data;
            this.postOptions = response.posts;
            this.roleOptions = response.roles;
            this.form.postIds = response.postIds;
            this.form.roleIds = response.roleIds;
            this.getOrderList();
            this.getReceiveList();
          });
        });
      },

      // 用户性别字典翻译
      typeFormat(row, column) {
        return this.selectDictLabel(this.typeOptions, row.peopleType);
      },

      /** 查询用户列表 */
      getList() {
        this.loading = true;
        this.queryParams.inviteFlag = 1;
        listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
            this.userList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      /** 查询订单管理列表 */
      getOrderList() {
        this.queryParams.inviteFlag = 1;
        this.queryOrderParams.userId = this.form.userId;
        listUserOrder(this.queryOrderParams).then(response => {
          this.userOrderList = response.rows;
          this.userOrderTotal = response.total;
        });
      },
      /** 查询订单管理列表 */
      getReceiveList(id) {
        this.queryReceiveParams.receiveId = this.form.userId;
        listUserReceive(this.queryReceiveParams).then(response => {
          this.receiveList = response.rows;
          this.receiveTotal = response.total;
        });
      },

      /** 查询用户订单列表 */
      getUserOrderList() {
        this.loading = true;
        this.queryParams.inviteFlag = 1;
        listUserOrder(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
            this.userList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      /** 查询用户列表 */
      getTypeList() {
        this.loading = true;
        this.queryTypeParams.peopleType = 1;
        listUserType(this.addDateRange(this.queryTypeParams, this.dateRange)).then(response => {
            this.userTypeList = response.rows;
            console.log(this.userTypeList)
            this.TypeTotal = response.total;
            console.log(this.TypeTotal)
            this.loading = false;
          }
        );
      },
      // 用户性别字典翻译
      sexFormat(row, column) {
        return this.selectDictLabel(this.sexOptions, row.sex);
      },

      // 用户状态修改
      handleStatusChange(row) {
        let text = row.status === "0" ? "启用" : "停用";
        this.$confirm('确认要"' + text + '""' + row.userName + '"用户吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return changeUserStatus(row.userId, row.status);
        }).then(() => {
          this.msgSuccess(text + "成功");
        }).catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
      },
      // 取消按钮
      cancel() {
        this.updateOpen = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          userId: undefined,
          deptId: undefined,
          userName: undefined,
          nickName: undefined,
          password: undefined,
          phonenumber: undefined,
          peopleType: undefined,
          email: undefined,
          sex: undefined,
          status: "0",
          remark: undefined,
          postIds: [],
          roleIds: []
        };
        this.resetForm("form");
        this.disabled = false;
      },

      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },

      /** 搜索按钮操作 */
      handleQuery() {
        console.log(this.queryParams)
        this.queryParams.page = 1;
        this.getTypeList();
      },
      handleTabClick() {
        this.tabActiveName = "first"
      },
      /** 查看地址操作 */
      handleInviteList(row) {
        this.user = row;
        //console.log(row)
        const userId = row.userId || this.ids;
        this.orderOpen = true;
        this.$nextTick(()=>{
          getUser(userId).then(response => {
            this.form = response.data;
            // this.getOrderList();
            // this.getReceiveList();
            this.getInviteUserList(row);
          });
        });
      },
      getInviteUserList(row) {
        this.loading = true;
        this.queryInviteParams.inviteFlag = 1;
        this.queryInviteParams.inviteUserId=this.form.userId
        listInviteUser(this.addDateRange(this.queryInviteParams, this.dateRange)).then(response => {
          this.userList1 = response.rows;
          this.userTotal = response.total;
          this.loading = false;
        });
      }
    }
  };
</script>
